//
//  ConcernViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/7/27.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "ConcernViewController.h"

#import "MoreDetailViewController.h"
#import "ChanelDetailViewController.h"
#import "DesignerDetailViewController.h"

#import "ChannelTableViewCell.h"
#import "FoundListCell.h"
#import "UIImage+GradientColor.h"

@interface ConcernViewController ()<UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIImageView *selectImg;
@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, assign) NSInteger isChannel;

@property (nonatomic,strong)  NSMutableArray  * designerArray;
@property (nonatomic,strong)  NSMutableArray  * channelArray;

@property (nonatomic,assign)  NSInteger       designerPage;
@property (nonatomic,assign)  NSInteger       channelPage;
@property (nonatomic,assign)  NSInteger       current_DesignerPage;
@property (nonatomic,assign)  NSInteger       current_ChannelPage;

@property (nonatomic,strong)  UIButton *noteBtn;

@end

@implementation ConcernViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"关注";
    self.isChannel = 0;
    self.designerArray = [NSMutableArray array];
    self.channelArray = [NSMutableArray array];
    
    [self setTopBar];
    [self setUI];
    
    _noteBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(79), ScreenX375(27))];
    [_noteBtn setTitleColor:REXADECIMALCOLOR(@"#f21934") forState:UIControlStateNormal];
    _noteBtn.titleLabel.font = Kfont(14);
    _noteBtn.layer.cornerRadius = ScreenX375(13.5);
    _noteBtn.layer.borderColor = REXADECIMALCOLOR(@"#f21934").CGColor;
    _noteBtn.layer.borderWidth = 1;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_noteBtn];
}

- (void)setTopBar {
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(230)) / 2, 0, ScreenX375(230), ScreenX375(31))];
    [self.view addSubview:titleView];
    
    UIView *titleBg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(230), ScreenX375(31))];
    titleBg.layer.cornerRadius = ScreenX375(15.5);
    titleBg.layer.borderWidth = 0.5;
    titleBg.layer.borderColor = REXADECIMALCOLOR(@"#eaeaea").CGColor;
    titleBg.layer.masksToBounds = YES;
    [titleView addSubview:titleBg];
    
    UIImage *bgImg = [UIImage gradientColorImageFromColors:@[REXADECIMALCOLOR(@"#fd4d4d"),REXADECIMALCOLOR(@"#ff1062")] gradientType:GradientTypeLeftToRight imgSize:CGSizeMake(ScreenX375(120), ScreenX375(31))];
    _selectImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(120), ScreenX375(31))];
    _selectImg.image = bgImg;
    _selectImg.layer.cornerRadius = ScreenX375(15.5);
    _selectImg.clipsToBounds = YES;
    [titleView addSubview:_selectImg];
    
    NSArray *noteArr = @[@"关注设计师",@"关注频道"];
    for (int i = 0; i < 2; i++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(i * ScreenX375(110), 0, ScreenX375(120), ScreenX375(31))];
        [button setTitle:noteArr[i] forState:UIControlStateNormal];
        [button setTitleColor:REXADECIMALCOLOR(@"#ffffff") forState:UIControlStateSelected];
        [button setTitleColor:REXADECIMALCOLOR(@"#888888") forState:UIControlStateNormal];
        button.titleLabel.font = Kfont(15);
        if (i == 0) {
            button.selected = YES;
            _selectBtn = button;
        }
        button.tag = 100 + i;
        [button addTarget:self action:@selector(typeClick:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:button];
    }
}

- (void)typeClick:(UIButton *)button {
    _selectBtn.selected = NO;
    button.selected = YES;
    _selectBtn = button;
    _isChannel = button.tag - 100;
    BaseTableView *tableView = [self.view viewWithTag:button.tag + 100];
    [tableView.mj_header beginRefreshing];
    if (button.tag == 100) {
        [UIView animateWithDuration:0.3 animations:^{
            self.selectImg.frame = CGRectMake(0, 0, ScreenX375(120), ScreenX375(31));
        }];
    }else {
        [UIView animateWithDuration:0.3 animations:^{
            self.selectImg.frame = CGRectMake(ScreenX375(110), 0, ScreenX375(120), ScreenX375(31));
        }];
    }
    [_scrollView setContentOffset:CGPointMake((button.tag - 100) * SCREEN_WIDTH, 0) animated:YES];
}

- (void)setUI {
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, ScreenX375(35), SCREEN_WIDTH, SCREEN_HEIGHT - ScreenX375(35))];
    _scrollView.showsVerticalScrollIndicator = false;
    _scrollView.showsHorizontalScrollIndicator = false;
    _scrollView.pagingEnabled = true;
    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 2, 0);
    [self.view addSubview:_scrollView];
    
    for (int i = 0; i < 2; i++) {
        BaseTableView *tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(35))];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor whiteColor];
        tableView.tag = 200 + i;
        tableView.rowHeight = ScreenX375(430);
        [_scrollView addSubview:tableView];
        
        __weak __typeof(self)weakSelf = self;
        tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            if (weakSelf.isChannel == 1) {
                weakSelf.current_ChannelPage = 1;
            }else {
                weakSelf.current_DesignerPage = 1;
            }
            
            
            NSString *url = [NSString stringWithFormat:@"%@api/getChannelConcernedList",REQUESTHEADER];
            if (weakSelf.isChannel == 0) {
                url = [NSString stringWithFormat:@"%@api/getUserConcernedList",REQUESTHEADER];
            }
            NSDictionary *dict = @{@"id":kNSUDefaultReadKey(@"userId"),@"page":@"1"};
            
            [HttpManager postHttpRequestByGet:url andParameter:dict success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
                if ([status isEqualToString:@"200"]) {
                    [tableView.mj_header endRefreshing];
                    NSError *error;
                    if (weakSelf.isChannel == 1) {
                        [weakSelf.channelArray removeAllObjects];
                        weakSelf.channelPage = [successResponse[@"data"][@"pages"] integerValue];
                        for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                            ChannelModel *model = [[ChannelModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.channelArray addObject:model];
                        }
                        if (weakSelf.channelPage == weakSelf.current_ChannelPage) {
                            tableView.mj_footer.hidden = YES;
                        }
                        [self.noteBtn setTitle:[NSString stringWithFormat:@"%@频道",successResponse[@"data"][@"total"]] forState:UIControlStateNormal];
                    }else {
                        [weakSelf.designerArray removeAllObjects];
                        weakSelf.designerPage = [successResponse[@"data"][@"pages"] integerValue];
                        for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                            FoundModel *model = [[FoundModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.designerArray addObject:model];
                        }
                        if (weakSelf.designerPage == weakSelf.current_DesignerPage) {
                            tableView.mj_footer.hidden = YES;
                        }
                        [self.noteBtn setTitle:[NSString stringWithFormat:@"%@设计师",successResponse[@"data"][@"total"]] forState:UIControlStateNormal];
                    }
                    [tableView reloadData];
                    
                }else{
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
                }
            } andFailure:^(id failureResponse) {
                [tableView.mj_header endRefreshing];
                [HttpManager showFail];
            }];
        }];
        
        tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            if (weakSelf.isChannel == 1) {
                weakSelf.current_ChannelPage++;
            }else {
                weakSelf.current_DesignerPage++;
            }
            
            NSString *url = [NSString stringWithFormat:@"%@api/getChannelConcernedList",REQUESTHEADER];
            NSDictionary *dict = @{@"id":kNSUDefaultReadKey(@"userId"),@"page":[NSNumber numberWithInteger:weakSelf.current_ChannelPage]};
            if (weakSelf.isChannel == 0) {
                url = [NSString stringWithFormat:@"%@api/getUserConcernedList",REQUESTHEADER];
                dict = @{@"id":kNSUDefaultReadKey(@"userId"),@"page":[NSNumber numberWithInteger:weakSelf.current_DesignerPage]};
            }
            
            [HttpManager postHttpRequestByGet:url andParameter:dict success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
                if ([status isEqualToString:@"200"]) {
                    [tableView.mj_footer endRefreshing];
                    NSError *error;
                    if (weakSelf.isChannel == 1) {
                        weakSelf.channelPage = [successResponse[@"data"][@"pages"] integerValue];
                        for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                            ChannelModel *model = [[ChannelModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.channelArray addObject:model];
                        }
                        if (weakSelf.channelPage == weakSelf.current_ChannelPage) {
                            tableView.mj_footer.hidden = YES;
                        }
                    }else {
                        weakSelf.designerPage = [successResponse[@"data"][@"pages"] integerValue];
                        for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                            FoundModel *model = [[FoundModel alloc] initWithDictionary:dic error:&error];
                            [weakSelf.designerArray addObject:model];
                        }
                        if (weakSelf.designerPage == weakSelf.current_DesignerPage) {
                            tableView.mj_footer.hidden = YES;
                        }
                    }
                    [tableView reloadData];
                    
                }else{
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
                }
            } andFailure:^(id failureResponse) {
                [tableView.mj_footer endRefreshing];
                [HttpManager showFail];
            }];
        }];
        
        if (i == 0) {
            [tableView.mj_header beginRefreshing];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 200) {
        return _designerArray.count;
    }
    return _channelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 200) {
        FoundListCell *cell = [FoundListCell cellWithTableView:tableView andIndexPath:indexPath];
        FoundModel *model = _designerArray[indexPath.row];
        cell.foundModel = model;
        return cell;
    }else {
        ChannelTableViewCell *cell = [ChannelTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
        cell.channelModel = _channelArray[indexPath.row];
        ChannelModel *model = _channelArray[indexPath.row];
        cell.concernClick = ^{
            [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/concernChannel",REQUESTHEADER] andParameter:@{@"userId":kNSUDefaultReadKey(@"userId"),@"channelId":model.Id} success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
                if ([status isEqualToString:@"200"]) {
                    if ([model.isFollow integerValue]) {
                        model.isFollow = @"0";
                        model.fensNum = [NSString stringWithFormat:@"%ld",[model.fensNum integerValue] - 1];
                        [HttpManager showNoteMsg:@"取消关注成功"];
                    }else {
                        model.isFollow = @"1";
                        [HttpManager showNoteMsg:@"关注成功"];
                        model.fensNum = [NSString stringWithFormat:@"%ld",[model.fensNum integerValue] + 1];
                    }
                    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                }else {
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
                }
            } andFailure:^(id failureResponse) {
                [HttpManager showFail];
            }];
        };
        return cell;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
        
        UIButton *button = [self.view viewWithTag:index + 100];
        _selectBtn.selected = NO;
        button.selected = YES;
        _selectBtn = button;
        if (button.tag == 100) {
            [UIView animateWithDuration:0.3 animations:^{
                self.selectImg.frame = CGRectMake(0, 0, ScreenX375(120), ScreenX375(31));
            }];
        }else {
            [UIView animateWithDuration:0.3 animations:^{
                self.selectImg.frame = CGRectMake(ScreenX375(110), 0, ScreenX375(120), ScreenX375(31));
            }];
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
        
        UIButton *button = [self.view viewWithTag:index + 100];
        _selectBtn.selected = NO;
        button.selected = YES;
        _selectBtn = button;
        _isChannel = button.tag - 100;
        BaseTableView *tableView = [self.view viewWithTag:button.tag + 100];
        [tableView.mj_header beginRefreshing];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 200) {
        PostersModel *model = _designerArray[indexPath.row];
        DesignerDetailViewController *vc = [[DesignerDetailViewController alloc] init];
        vc.designerId = model.Id;
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        ChannelModel *model = _channelArray[indexPath.row];
        ChanelDetailViewController *vc = [[ChanelDetailViewController alloc] init];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
